<template>
  <div class="product-management-container">
    <!-- 1. 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchParams" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchParams.keyword" placeholder="输入关键词搜索" clearable @clear="handleSearch"></el-input>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="searchParams.status" placeholder="全部状态" clearable @change="handleSearch">
            <el-option label="在售" :value="1"></el-option>
            <el-option label="已下架" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 2. 功能按钮和数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <el-button type="success" @click="openDialog('add')">新增商品</el-button>
        </div>
      </template>
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        <el-table-column prop="productId" label="ID" width="80" />
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="price" label="价格" width="120" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '在售' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDialog('edit', scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status === 1" size="small" type="danger" @click="handleDelist(scope.row)">下架</el-button>
            <el-button v-else size="small" type="warning" @click="handleRelist(scope.row)">上架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 3. 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @close="closeDialog">
      <el-form :model="productForm" ref="productFormRef" label-width="100px">
        <el-form-item label="商品名称" prop="name" required>
          <el-input v-model="productForm.name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price" required>
          <el-input-number v-model="productForm.price" :precision="2" :step="1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="productForm.description"></el-input>
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <el-input v-model="productForm.imageUrl"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { getProductList, addProduct, updateProduct } from '@/api/admin/product';
import { ElMessage, ElMessageBox } from 'element-plus';

// --- 响应式数据 ---
const loading = ref(false);
const tableData = ref([]);
const searchParams = reactive({
  keyword: '',
  status: null
});

const dialogVisible = ref(false);
const dialogMode = ref('add'); // 'add' or 'edit'
const dialogTitle = computed(() => dialogMode.value === 'add' ? '新增商品' : '编辑商品');
const productFormRef = ref(null);
const productForm = reactive({
  productId: null,
  name: '',
  price: 0,
  description: '',
  imageUrl: ''
});

// --- 方法 ---

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getProductList(searchParams);
    if (res.code === 200) {
      tableData.value = res.data;
    } else {
      ElMessage.error(res.message || '获取列表失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 搜索和重置
const handleSearch = () => {
  fetchData();
};
const resetSearch = () => {
  searchParams.keyword = '';
  searchParams.status = null;
  fetchData();
};

// 打开弹窗
const openDialog = (mode, rowData = null) => {
  dialogMode.value = mode;
  if (mode === 'edit' && rowData) {
    // 编辑模式，回填数据
    Object.assign(productForm, rowData);
  }
  dialogVisible.value = true;
};

// 关闭并重置弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  productFormRef.value?.resetFields(); // 重置表单验证
  // 手动清空表单数据
  Object.assign(productForm, {
    productId: null, name: '', price: 0, description: '', imageUrl: ''
  });
};

// 提交表单 (新增或更新)
const submitForm = async () => {
  if (!productForm.name || productForm.price <= 0) {
    ElMessage.warning('请填写完整的商品名称和有效的价格');
    return;
  }

  try {
    let res;
    if (dialogMode.value === 'add') {
      res = await addProduct(productForm);
    } else {
      res = await updateProduct(productForm);
    }

    if (res.code === 200) {
      ElMessage.success(res.message || '操作成功');
      closeDialog();
      fetchData(); // 刷新列表
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后再试');
  }
};

// 下架商品
const handleDelist = (row) => {
  ElMessageBox.confirm(`确定要下架商品【${row.name}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await updateProduct({ productId: row.productId, status: 0 });
    if(res.code === 200) {
      ElMessage.success('下架成功');
      fetchData();
    } else {
      ElMessage.error(res.message || '下架失败');
    }
  }).catch(() => {});
};

// 上架商品
const handleRelist = async (row) => {
  const res = await updateProduct({ productId: row.productId, status: 1 });
  if(res.code === 200) {
    ElMessage.success('上架成功');
    fetchData();
  } else {
    ElMessage.error(res.message || '上架失败');
  }
}

// 组件挂载时获取初始数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.product-management-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>